// 千分位分隔符指令
import { Directive, DirectiveBinding } from 'vue'

const thousandSeparator: Directive = {
  mounted(el: any, binding: DirectiveBinding) {
    if (el.tagName.toLocaleUpperCase() !== 'INPUT') {
      el = el.getElementsByTagName('input')[0]
    }

    el.setAttribute('class', 'el-input__inner placeholder_left')
    el.style.textAlign = 'right'

    const value = binding.value
    if (value !== null && !isNaN(Number(value))) {
      el.value = parseFloat(value).toLocaleString('en-US', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      })
    }

    el.onfocus = (e: any) => {
      const a = e.target.value.replace(/,/g, '') // 去除千分号的','
      el.value = a
    }
  },
  updated(el: any, binding: DirectiveBinding) {
    if (el.tagName.toLocaleUpperCase() !== 'INPUT') {
      el = el.getElementsByTagName('input')[0]
    }

    const value = binding.value
    if (value !== null && !isNaN(Number(value))) {
      el.value = parseFloat(value).toLocaleString('en-US', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      })
    }
  },
}

export default thousandSeparator
